$(function () {
  // 面包屑导航
  function nav() {
    let element = layui.element
    element.init($('.x-nav').html(`
    <span class="layui-breadcrumb">
      <a href="">首页</a>
      <a href="">标签管理</a>
      <a><cite>正文</cite></a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:5px;float:right" onclick="location.reload()" title="刷新">
    <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
    `))
  }
  nav()

  let form = layui.form

  // PART ============== 渲染页面 ==============

  // 获取本地token令牌
  let token = localStorage.getItem('x-token')

  let querydata = {
    "tagname": '',
    "page": '',
    "limit": '',
    "x-token": token
  }

  async function gettagRender() {
    const { data: { data } } = await axios.get('/ydd_tag/list', {
      params: querydata
    })
    // 判断数据是否为空
    if (data.data.length === 0) {
      layer.msg('没有相关数据数据')
    }
    $('tbody').html(data.data.map((item, index) => {
      const { tagname, id } = item
      return `
      <tr>
        <td>${index + 1}</td>
        <td>${id}</td>
        <td>${tagname}</td>
        <td class="handle">
          <a class="edit" href="javascript:;" data-id=${id}>
            <i class="handle-icon layui-icon layui-icon-util"></i>
          </a>
          <a class="delet" href="javascript:;" data-id=${id}>
            <i class="handle-icon layui-icon layui-icon-delete"></i>
          </a>
        </td>
      </tr>
      `
    }).join(''))
    renderPage(data.count)
  }

  gettagRender()

  // PART ============== 分页 ==============

  function renderPage(count) {
    var laypage = layui.laypage;

    //执行一个laypage实例
    laypage.render({
      elem: 'pagebox', //注意，这里的 test1 是 ID，不用加 # 号
      count: count, //数据总数，从服务端得到
      limit: querydata.limit,
      curr: querydata.page,
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      limits: [1, 2, 3, 5, 10],
      // laypage.render 函数调用或分页切换时触发 jump
      // 如果是laypage.render 函数触发 first 是 true
      // 分页切换时触发 first 是 undefined
      jump: function (obj, first) {
        // querydata.page = obj.curr
        // getRender()
        if (!first) {
          querydata.page = obj.curr
          querydata.limit = obj.limit
          gettagRender()
        }
      }
    })
  }

  // PART ============== 新增按钮 ==============

  // 添加按钮弹出层样式
  let addTagFormstr = `
  <form id="addForm" class="layui-form">
    <!-- 第一行 标签名称 -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">标签名称</label>
      <div class="layui-input-block">
        <input type="text" name="tagname" required lay-verify="required" placeholder="请输入标签名" autocomplete="off"
          class="layui-input">
      </div>
    </div>
    <!-- 按钮 -->
    <div class="layui-form-item">
      <div class="layui-input-block subbtn">
        <button type="button" id="callOff" class="layui-btn layui-bg-gray">取消</button>
        <button lay-submit class="layui-btn">确定</button>
      </div>
    </div>
  </form>
  `

  // 给新增按钮绑定点击事件
  let tagAddform
  $('#form #addbtn').on('click', function (e) {
    tagAddform = layer.open({
      content: addTagFormstr,
      type: 1,
      title: '添加标签',
      area: ['600px', '200px'],
      skin: 'layui-layer-lan',
      offset: ['170px']
    })
  })

  // 给取消按钮绑定关闭弹出层功能
  $('body').on('click', '#callOff', function () {
    layer.close(tagAddform)
  })

  // 给确定按钮绑定提交事件
  $('body').on('submit', '#addForm', async function (e) {
    e.preventDefault()
    // console.log('l')
    const data = $(this).serialize()
    // console.log(data)
    const res = await axios.post('/ydd_tag/add', data)
    gettagRender()
    layer.close(tagAddform)
    layer.msg('数据添加成功')
  })

  // PART ============== 编辑按钮 ==============
  let editTagFormstr = `
  <form id="editForm" class="layui-form" lay-filter="editText">
    <!-- 第一行 分类id -->
    <div class="layui-form-item" id="ids">
      <label class="layui-form-label">id</label>
      <div class="layui-input-block">
        <input type="text" name="id" required lay-verify="required" placeholder="请输入id" autocomplete="off"
          class="layui-input">
      </div>
    </div>
    <!-- 第一行 标签名称 -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">标签名称</label>
      <div class="layui-input-block">
        <input type="text" name="tagname" required lay-verify="required" placeholder="请输入标签名" autocomplete="off"
          class="layui-input">
      </div>
    </div>
    <!-- 按钮 -->
    <div class="layui-form-item">
      <div class="layui-input-block subbtn">
        <button type="button" id="callOff" class="layui-btn layui-bg-gray">取消</button>
        <button lay-submit class="layui-btn">确定</button>
      </div>
    </div>
  </form>
  `
  let tagEditform
  $('body').on('click', '.handle .edit', async function () {
    // 弹出面板
    tagEditform = layer.open({
      content: editTagFormstr,
      type: 1,
      title: '编辑标签',
      area: ['600px', '200px'],
      skin: 'layui-layer-lan',
      offset: ['170px']
    })

    const id = $(this).attr('data-id')
    const res = await axios.get('/ydd_tag/rowInfo', {
      params: {
        id,
        "x-token": token
      }
    })
    const tagname = res.data.data.tagname
    const ids = res.data.data.id
    //给表单赋值
    //formedit 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
    form.val("editText", {
      "id": ids,
      "tagname": tagname
    })
  })

  // 给确定按钮绑定提交事件
  $('body').on('submit', '#editForm', async function (e) {
    e.preventDefault()
    const editdata = $(this).serialize()
    const res = await axios.post('/ydd_tag/update', editdata)
    gettagRender()
    layer.close(tagEditform)
  })

  // 给取消按钮绑定关闭弹出层功能
  $('body').on('click', '#callOff', function () {
    layer.close(tagEditform)
  })

  // PART ============== 删除按钮 ==============

  $('body').on('click', '.handle .delet', async function () {
    const id = $(this).attr('data-id')
    const res = await axios.get('/ydd_tag/del', {
      params: {
        "id": id,
        "x-token": token
      }
    })
    gettagRender()
    layer.msg('数据删除成功')
  })

  // PART ============== 全部数据 ==============
  async function getbothRender() {
    const { data: { data } } = await axios.get('/ydd_tag/all', {
      params: {
        "x-token": token
      }
    })
    console.log(data)
    $('#tableboth').html(data.map((item, index) => {
      const { tagname, id } = item
      return `
      <tr>
        <td>${index + 1}</td>
        <td>${id}</td>
        <td>${tagname}</td>
        <td class="handle">
          <a class="edit" href="javascript:;" data-id=${id}>
            <i class="handle-icon layui-icon layui-icon-util"></i>
          </a>
          <a class="delet" href="javascript:;" data-id=${id}>
            <i class="handle-icon layui-icon layui-icon-delete"></i>
          </a>
        </td>
      </tr>
      `
    }).join(''))
  }

  getbothRender()

  // PART ============== 筛选功能 ==============
  $("#tagScreenForm").on('submit', function (e) {
    e.preventDefault()
    const data = $('#nameinput').val()
    querydata.tagname = data
    gettagRender()
    $('#tagScreenForm [type="reset"]').click()
  })

  // PART ============== 导出数据 ==============

  $('#exportbtn').on('click', function () {
    var blob = new Blob([document.getElementsByClassName("exportTable")[0].outerHTML], {
      type: "text/plain;charset=utf-8"
    })
    saveAs(blob, "export.xls")
  })
})